import axios from 'axios'
import Qs from 'qs'
import { Notification } from 'element-ui';
import util from './util'
import router from '../router'
import { Base64 } from 'js-base64'; // npm install --save js-base64
import $ from 'jquery';  //$ npm install jquery --save 用的同步功能


class HttpRequest {
  constructor(baseUrl) {
    if (baseUrl) {
      this.baseUrl = baseUrl;
    } else {
      this.baseUrl = 'http://localhost:8885';
    }
    this.baseImage = this.baseUrl + "/file/show/";
    this.queue = {}
  }
  getInsideConfig(retype) {
    if (!retype) {
      retype = 'application/x-www-form-urlencoded'
    }
    let config = {
      baseURL: this.baseUrl,
      timeout: 30000,
      withCredentials: true,
      headers: {
        'Content-Type': retype,
        "token": util.getToken(),
        "refresh": util.getRefresh()
      }
    }
    return config
  }
  destroy(url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }

  interceptors(instance, ops) {

    let ref = this;
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        //  Spin.show() // 不建议开启，因为界面不友好
      }
      if (config.method == 'post' && config.headers['Content-Type'] == 'application/json') {
        config.data = JSON.stringify(config.data)
      }
      return config;
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
       return this.parseData(res);
    }, error => {
      let errorInfo = error.response;
      if (errorInfo && errorInfo.data) {

        //token 过期
        if (errorInfo.data.code && errorInfo.data.code == "token_expired") {
          var storerefresh = util.getRefresh();
          if (!storerefresh) {
            router.push({ path: "/login" });
          }
          var refresh = Base64.decode(storerefresh.split(".")[0]);
          if (refresh > new Date().getTime()) { 

              let config = error.config;
              var result=null;
              $.ajax({
                url:this.baseUrl + "/user/refresh/token",//url路径
                type:'GET', //GET
                async:false, //或false,是否异步
                data:{//参数 
                },
                timeout:5000, //超时时间
                dataType:'json', //返回的数据格式：
                headers:{'Content-Type':'application/json;charset=utf8','token':config.headers.token,'refresh':config.headers.refresh},
                beforeSend:function(xhr){
                  xhr.setRequestHeader("organId",'1333333333');
                },
                success:function(data,textStatus,jqXHR){
                  util.setToken(data.token);
                  util.setRefresh(data.refresh);
                  config.headers.token=data.token;
                  config.headers.refresh=data.refresh;
                  result= ref.request(error.config);

                },
                error:function(xhr,textStatus){
                    result={"code":"401","errMsg":"刷新token错误"};
                },
                complete:function(){
                }
              })
             return result;
          } else {
            router.push({ path: "/login" });
            return;
          }
        }
        //refresh拦截
        if (errorInfo.data.code && errorInfo.data.code == "refresh_expired") {
          router.push({ path: "/login" });
          return;
        }

        let errinfo = "error";
        if (errorInfo.data.errMsg) {
          errinfo = errorInfo.data.errMsg;
        } else {
          errinfo = JSON.stringify(errorInfo.data);
        }
        Notification.error({
          title: '错误',
          message: errinfo
        });
      } else {
        Notification.error({
          title: '错误',
          message: JSON.stringify(error.message)
        });
      }
      return Promise.reject(error)
    })
  }
  request(options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }

  parseData(res){
    if (res.data && res.data.code && res.data.code != "200") {
      Notification.error({ 'title': '请求错误', 'message': res.data.errMsg })
      return Promise.reject(res)
    } else if (res.data && res.data.code && res.data.code == "200" && res.data.data) {
      return (res.data.data);
    }
    return res.data
  }

  // get 请求
  get(url) {
    const instance = axios.create()
    let options = Object.assign(this.getInsideConfig(), { 'method': 'GET', 'url': url })
    this.interceptors(instance, options)
    return instance(options)
  }
  // 请求json
  postJson(url, data) {
    const instance = axios.create()
    let reconfig = this.getInsideConfig('application/json')
    let options = Object.assign(reconfig, { 'data': data, 'url': url, 'method': 'POST' })
    this.interceptors(instance, options.url)
    return instance(options)
  }

  // post form
  post(url, data) {
    const instance = axios.create()
    let reconfig = this.getInsideConfig()
    let options = Object.assign(reconfig, { 'data': Qs.stringify(data), 'url': url, 'method': 'POST' })
    this.interceptors(instance, options.url)
    return instance(options)
  }

  // post form 上传文件和表单
  postFormData(url, data) {
    const instance = axios.create()
    let reconfig = this.getInsideConfig("multipart/form-data")
    let param = null;
    if (data && !(data instanceof FormData)) {
      param = new FormData();
      for (var key in data) {
        param.append(key, data[key]);
      }
    } else {
      param = data;
    }
    let options = Object.assign(reconfig, { 'data': param, 'url': url, 'method': 'POST' })
    this.interceptors(instance, options.url)
    return instance(options)
  }


}
export default HttpRequest
